<template>
  <div>
    <van-nav-bar
      title="乐购"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    >
    </van-nav-bar>
      <van-field class="field" v-model="iptVal" placeholder="搜索" />
    <ul v-if="flag">
      <li v-for="item in searchList" :key="item.id" @click="goHome(item)">
        {{ item.name }}
      </li>
    </ul>
    <div class="map">
      <h2>显示当前位置:</h2>
      <div id="container"></div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions, mapGetters } from "vuex";
export default {
  data() {
    return {
      iptVal: "",
      cityText: "",
      searchList: [],
      flag: true,
    };
  },
  created() {},
  mounted() {
    if (this.$store.state.cityInfo.name) {
      var cityInfo = this.$store.state.cityInfo;
      var map = new AMap.Map("container", {
        zoom: 15,
        center: [cityInfo.location.lng, cityInfo.location.lat],
      });
      var marker = new AMap.Marker({
        position: [cityInfo.location.lng, cityInfo.location.lat],
      });
      map.add(marker);
      return;
    }
    var _this = this;
    AMap.plugin("AMap.CitySearch", function () {
      var citySearch = new AMap.CitySearch();
      citySearch.getLocalCity(function (status, result) {
        if (status === "complete" && result.info === "OK") {
          // 查询成功，result即为当前所在城市信息
          // console.log(result)
          _this.cityText = result.city;
        }
      });
    });
    var map = new AMap.Map("container", {
      zoom: 8,
    });
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1);
    },
    ...mapMutations(["uptCityInfo"]),
    onClickLeft() {
      this.$router.push(`/home`);
    },
    goHome(val) {
      this.uptCityInfo(val);
      console.log(val);
      this.$router.push("/home");
    },
  },
  watch: {
    iptVal() {
      if (this.iptVal == "") {
        this.flage = false;
      } else {
        this.flage = true;
      }
      var _this = this;
      AMap.plugin("AMap.Autocomplete", function () {
        // 实例化Autocomplete
        var autoOptions = {
          //city 限定城市，默认全国
          city: _this.cityText,
        };
        var autoComplete = new AMap.Autocomplete(autoOptions);
        autoComplete.search(_this.iptVal, function (status, result) {
          console.log(result);
          _this.searchList = result.tips;
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.field {
  width: 337px;
  height: 44px;
  border: 2px solid rgb(196, 189, 189);
  border-radius: 5px;
  margin: 10px auto;
}
.map {
  width: 100%;
  height: 250px;
  position: absolute;
  bottom: 0px;
  #container {
    width: 375px;
    height: 200px;
  }
  h2 {
    margin-left: 5px;
    text-align: left;
  }
}
ul {
  height: 300px;
  overflow: auto;
  li {
    text-align: left;
    padding: 0.26667rem 0.4rem 0.26667rem 0.4rem;
  }
}
</style>